<?php
namespace app\store\controller;
use think\Db;
use think\Controller;
use app\common\controller\IdexBaseController;
use app\index\model\UserModel;
use app\index\model\ComplainModel;
use app\index\model\MemberVerifModel;
use app\index\model\AgentModel;
use app\index\model\UnionModel;
use app\index\model\Qianyue;
use app\api\controller\Index;

/**
 * 钱包
 */
class Wallet extends Controller {

	protected function _initialize() {
		parent::_initialize();
		 
	}
	
	/************************************2018-03-07 lucifer start*****************************************/
	//鼓励金设置
	function yun_pay(){
		//获取商家信息
		$agent_info = db('info_agent')->where('id',session("agent_id"))->find();
		
		$this->assign('agent_info',$agent_info);
		
		return $this->fetch();
	}
	
	//商家收款二维码
	function shop_payment(){
		//获取商家信息
		$agent_info = db('info_agent')->where('id',session("agent_id"))->find();
		//获取当前商家分店
		$chains = db('agent_store')
					->where('agent_id',$agent_info['id'])
					->where('state',1)
					->select();
		
		$code_url="http://".$_SERVER['HTTP_HOST']."/index/pay/qrcode_pay?agent_id=".$agent_info['id'];
		
		
		$this->assign('code_url',$code_url);
		$this->assign('chains',$chains);
		return $this->fetch();
	}
	
	
	
	
	/************************************2018-03-07 lucifer end*****************************************/
	
	
	
	public function index(){
		$list = Db::name('member')->field('credit3,credit2,credit1')-> where('id', input('uid')) -> find();
		return $this -> toJson('200', '', $list);
	}
	
	//充值
	public function chongz(){
		if(input('money')){
			$money=input('money');
			$member=$data = ['uid'=>input('uid'),'price' => $money,'zf'=>'+'];
			
			Db::name('mall_paylog')->insert($data);
			
			$list = Db::name('member')->field('credit2')-> where('id', input('uid')) -> find();
			$money=$money+$list['credit2'];
			$list1=Db::name('member')->where('id',input('uid'))->setField('credit2', $money);
			return $this -> toJson('200', '充值成功', $member);
		}else{
			$list = Db::name('member')->field('mobile')-> where('id', input('uid')) -> find();
		return $this -> toJson('200', '', $list);
		}
	}
	/**
	 * 快速购买商品
	 */
	public function fast_goods_info(){
		if(!input('goods_id')||!input("store_id")){
			return $this -> toJson('404', '参数错误', '');
		}
		$store=db('info_agent')->find(input("store_id"));
		$where['agent_id']=input("store_id");
		$where['goods_id']=input("goods_id");
		$where['stock']=['>',0];
		if(input('chain_id')){
			$where['chain_id']=input("chain_id");
		}else{
			$where['chain_id']=0;
		}
		$chain_goods=db("mall_goodsstock")->where($where)->find();
		if($chain_goods){
			$goods=db('line_goods')->find(input("goods_id"));
			return json(["code"=>200,"store"=>$store,"goods"=>$goods,"chain_goods"=>$chain_goods]);
		}else{
			return $this -> toJson('404', '商品库存不足请做入库处理', '');
		}
	}
	/**
	 * 后台扫码鼓励金兑现
	 */
	public function exchange(){
		$store_id=input("store_id");
		$sid=input("session_id");
		$agent=db("info_agent")->find($store_id);
		if(!$agent||!$sid){
			return $this -> toJson('406', '非法兑现!','');
		}
		$member=db("member")->find($agent['u_id']);
		if(!$member||($member['session_id']!=$sid)){
			return $this -> toJson('406', '未通过系统验证,无法完成兑现','');
		}
		$value=input("value");//兑现余额
		$scores=$value*10;
		if($agent['score']<=$scores){
			return $this -> toJson('406', '鼓励金不足!','');
		}else{
			$mem=new Member();
			$result = $mem -> insbalch($agent['id'],"鼓励金兑现增加余额",$value,15,0,1);
			$result1 = $mem ->insscoch($agent['id'],"鼓励金兑现扣除鼓励金",-$scores,15,0);
			if($result&&$result1){
				//获取分销设置  
				$distibution=getDisbution();
				//平台手续费
				$poundage = bcmul($value, $distibution['score_to_money']/100, 2);
				//扣除商家余额
				db('info_agent')->where('id', $agent['id'])->setDec('store_balance', $poundage);
				//新增商家余额变化日志
				$mem->agent_charge($agent['id'],19,1,0,"鼓励金兑换余额手续费",-$poundage,1,0,0);
				//新增平台佣金
				db('member')->where('id', 1)->setInc('credit3', $poundage);
				//更新平台佣金日志
				$mem->money_change(1,$agent['id'],'credit3',$poundage,"收取商家".$agent['store_name']."鼓励金转余额手续费",1,0,0,0);
				
				return $this -> toJson('200', '兑现成功!','');
			}else{
				return $this -> toJson('406', '兑现失败!','');
			}
		}
	}
	/**
	 * 前台鼓励金兑现
	 */
	public function exchange2(){
		$agent=db("info_agent")->find(session("agent_id"));
		if(!$agent){
			return $this -> toJson('406', '非法兑现!','');
		}
		
		$value=input("value");//兑现金额
		$scores=$value*10;
		if($agent['score']<$scores){
			return json(['code'=>405,'msg'=>'鼓励金不足']);
		}else{
			$mem=new Member();
			$result = $mem -> insbalch($agent['id'],"鼓励金兑现增加余额",$value,15,0,1);
			$result1 = $mem ->insscoch($agent['id'],"鼓励金兑现扣除鼓励金",-$scores,15,0);
			if($result&&$result1){
				//获取分销设置  
				$distibution=getDisbution();
				//平台手续费
				$poundage = bcmul($value, $distibution['score_to_money']/100, 2);
				//扣除商家余额
				db('info_agent')->where('id', $agent['id'])->setDec('store_balance', $poundage);
				//新增商家余额变化日志
				$mem->agent_charge($agent['id'],19,1,0,"鼓励金兑换余额手续费",-$poundage,1,0,0);
				//新增平台佣金
				db('member')->where('id', 1)->setInc('credit3', $poundage);
				//更新平台佣金日志
				$mem->money_change(1,$agent['id'],'credit3',$poundage,"收取商家".$agent['store_name']."鼓励金转余额手续费",1,0,0,0);
				return json(['code'=>200,'msg'=>'兑现成功']);
			}else{
				return json(['code'=>406,'msg'=>'兑现失败']);
			}
		}
	}
	//提现
	public function gettixian(){
		$tx=Db::name("member")->alias('a')
		 ->join('mall_cash b','a.id = b.uid','LEFT')
		 ->field('b.bank_account,b.card_no,a.credit2')->where("a.id",input("uid"))->find();
	     return $this->toJson(200,'',$tx);
	}
	
	//鼓励金消费
	public function jifen(){
		$tx=Db::name("mall_score")->alias('a')
		 ->join('info_agent b','b.id = a.agent_id','LEFT')
		 ->field('a.*,b.store_name')
		 ->where("a.user_id",input("uid"))->select();
	     return $this->toJson(200,'',$tx);
		
		
	}
	//商家鼓励金
	public function shangjif(){
			$field = 'm.*,b.store_name';	
			$list=Db::name("mall_consmember")->alias('m')
			->join('info_agent b','m.agent_id=b.id')
			->field($field) 
			->where('m.u_id',input("uid"))
			->select();

		return $this->toJson(200,'',$list);
	}	
	//商家鼓励金记录
    public function shop_score(){
    	
		//根据当前用户获取商户id 
		$agent_id = Db::name('info_agent')->where('u_id',input('uid'))->value('id');
		
		if($agent_id){
			$score_list = Db::name('mall_score_charge')->where('agent_id',$agent_id)->order('add_time asc')->select();
		
			for($i=0;$i<count($score_list);$i++){
				
				if($i==0){
					$score_list[$i]['balance'] = $score_list[$i]['score'];
				}else{
					$score_list[$i]['balance'] = $score_list[$i-1]['balance'] + $score_list[$i]['score'];
				}
			}
			return $this->toJson(200,'',$score_list);
		}
    }	
	
	/*
	 * 用户鼓励金记录
	 */
	public function memberjifen(){
		$u_id = request() -> param('uid');
		$list['jifen']=Db::name("line_exchangelog")->where('line_member_id',$u_id)->select();
		$list['sn'] = order_create_no();
		return $this->toJson(200,'',$list);
	}
	
	/*
	 * 提现记录表
	 */
	public function tixianjilu(){
		$uid = request() -> param('uid');
		$list=Db::name("mall_cashmanage")->where('uid',$uid)->where('user_type',1)->select();
		/*foreach($list as $k=>$v){
			$data[]=iunserializer($v['message']);
		}
		//$a=iunserializer($site['value']);
*/
		return $this->toJson(200,'',$list);
	}
	
	//提现中
  public function tixianz(){
  	$money=input('zmoney') - input('money');
  	$member=$data = ['uid'=>input('uid'),'price' => input('money'),'add_time'=>input('time'),'zf'=>'-','title'=>'提现中'];
	Db::name('mall_paylog')->insert($data);
  	$list1=Db::name('member')->where('id',input('uid'))->setField('credit2', $money);
  	return $this -> toJson('200', '提现中');
  }
  
  //余额变化
  
  public function xiaofei(){
  		$xiaofei=Db::name('mall_corepaylog')->where('uid',input('uid'))->select();//已完成

		return json(['xiaofei'=>$xiaofei]);
  }
  
  	//用户余额记录
    public function yue_record(){
    	
		$credits_list = Db::name('log_agent_charge')
						->where('uid',input('uid'))
						->where('credittype','credit2')
						->order('add_time asc')
						->select();
		
		if($credits_list){
			
			for($i=0;$i<count($credits_list);$i++){
				
				if($i==0){
					$credits_list[$i]['balance'] = $credits_list[$i]['price'];
				}else{
					$credits_list[$i]['balance'] = $credits_list[$i-1]['balance'] + $credits_list[$i]['price'];
				}
			}
			return $this->toJson(200,'',$credits_list);
		}else{
			return $this->toJson(402,'暂无记录');
		}
    }	
	
	//获取店铺收款方数据
	public function agent_shou(){
		$agent=Db::name('info_agent')->where('u_id',input('agent_id'))->find();
		$agent['sn'] = order_create_no();
		return $this->toJson(200,'',$agent);
	}
	
  //获取收款方数据
	public function shou(){
		$list=Db::name('member')->where('id',input('getmoney_uid'))->find();
		$list['sn'] = order_create_no();
		return $this->toJson(200,'',$list);
	} 	
	/**
	 * 显示提现银行卡列表
	 */
	public function get_bankcard(){
		$user_info = db('member')->where('id',input('uid'))->find();
		//检查用户是否通过审核
		if($user_info['is_credentials'] == 2){
			$token=md5_salt($user_info['id'],config("salt"));
			$user_info['token']=$token;
			return $this->toJson(200,'',$user_info);
		}else{
			return $this->toJson(408, '审核未通过');
		}
	}
	
	//提现中
    public function tixian(){
    	
    	$user = db('member')->where('id',input('uid'))->find();
		
		if($user['credit2'] >= intval(input('tixian_money'))){
			$now_time = date('H:i:s',time());
			$star_time = date('09:00:00',time());
			$end_time = date('17:00:00',time());
			if($now_time<$star_time||$now_time>$end_time)  {
				return $this -> toJson(408, '请在9:00~17:00时间段做提现操作');
			}
			
			if(input('type')==1){
				$map['createtime'] = ['between',[date('Y-m-d 00:00:00',time()),date('Y-m-d 23:59:59',time())]];
				$map['cash_status'] = array('in','1,2');
				$map['user_type'] = 1;
				$map['type'] = 1;
				$map['uid'] = input('uid');
				$balancesum = db('mall_cashmanage')->where($map)->sum('balance');
				if($balancesum+input('tixian_money')>1000)  {
					return $this -> toJson(408, '提现额度不足');
				}
				
				//手续费0.65%
				//$poundage = 0.0065;	
				$poundage = 0;		
				//$jian_money = $poundage*input('tixian_money')+2;			//提现手续费
				$jian_money = 2;			//提现手续费
				$act_money = floatval(input('tixian_money'))-floatval($jian_money);
				$balance = floatval($user['credit2'])-floatval(input('tixian_money'));
			}else{
				//手续费0.6%
				//$poundage = 0.006;
				$poundage = 0;			
				//$jian_money = $poundage*input('tixian_money');			//提现手续费
				$jian_money = 0;			//提现手续费
				$act_money = floatval(input('tixian_money'))-floatval($jian_money);
				$balance = floatval($user['credit2'])-floatval(input('tixian_money'));
			}			
			//减用余额
			$result = db('member')->where('id', $user['id'])->update(['credit2' => $balance]);
			//新增资金变化
			$credits['uid'] 			= $user['id'];
			$credits['tid'] 			= 0;
			$credits['credittype'] 		= 'credit2';
			$credits['price'] 			= -input('tixian_money');
			$credits['add_time'] 		= now_time();
			$credits['remark'] 			= '余额提现';
			$credits['type'] 			= 2;			//'0.默认1.佣金2.提现3.红包4.收付款';
					
			$result2 = db('mall_credits')->insert($credits);
					
			if($result){
				try {
					//获取提现方式
					$bank_info = db('mall_cash')->where('uid',input('uid'))->order('add_time desc')->find();
				
					//需要处理时间
					if(input('type') == 1){
						$needtime = date('Y-m-d H:i:s',time()+7200);
					}elseif(input('type') == 2){
						$needtime = date('Y-m-d H:i:s',time()+86400);
					}else{
						$needtime = date('Y-m-d H:i:s',time()+7200);
					}
				
					//新增提现记录
					$cashmanage['uid'] 				=  $user['id'];
					$cashmanage['user_type'] 		=  1;
					$cashmanage['type'] 			=  input('type');
					$cashmanage['balance'] 			=  input('tixian_money');
					$cashmanage['cash_type'] 		=  1;
					$cashmanage['actual_balance'] 	=  $act_money;
					$cashmanage['counter_fee'] 		=  $jian_money;
					$cashmanage['fee'] 				=  $poundage;
					$cashmanage['message'] 			=  $user['bank_account'];
					$cashmanage['cash_status'] 		=  1;
					$cashmanage['createtime'] 		=  now_time();
					$cashmanage['needtime'] 		=  $needtime;
					$cashmanage['card_no'] 			=  $user['card_no'];
					$cashmanage['bank_mobile'] 		=  $user['bank_mobile'];
					$cashmanage['bank_username'] 	=  $user['bank_username'];
					
					
					$result1 = db('mall_cashmanage')->insert($cashmanage); 
				
					// 获取短信模板
					$template = db('sms_template') -> find(5);
					$msg['name'] = $user['nick_name'];
					//财务电话
					$cw_mobile = config('cw_mobile');
					//发送短信，提醒商家
					$msg = send_sms($cw_mobile, $template['tid'], json_encode($msg), $template['sign_name']);
					
					
					return $this -> toJson('200', '提现成功');
					
				}catch(Exception $e) {
					return $this -> toJson('408', $e);
				}
			}else{
				return $this -> toJson('402', '申请提现失败');
			}
		}else{
			return $this -> toJson('400', '余额不足');
		}
    }

	//添加银行卡信息
	function add_bank(){
		$code = input('verifycode');
		
		if($code){
			$result = check_sendcode(input('mobile'), $code, '绑定银行卡');
			if ($result != 1) {
				return $this->toJson(408, '验证码错误或过期！');
			}else{
				$user = Db::name('member')->where('id', input('uid'))->find();
				
				if($user){
					
					$data['uid'] 			= $user['id'];
					$data['user_type'] 		= $user['agent_type'];
					$data['type'] 			= 1;
					$data['default'] 		= 1;
					$data['add_time'] 		= now_time();
					$data['bank_account'] 	= input('bank_name');
					$data['card_no'] 		= input('bank_num');
					$data['bank_username'] 	= input('user_name');
					
					$result = db('mall_cash')->insert($data);
					$cut_id = db('mall_cash')->getLastInsID();
					
					$result = db('mall_cash')->where('id','neq',$cut_id)->where('uid',$user['id'])->delete();
					
					return $this -> toJson(200, "绑定成功！");
				}else{
					return $this -> toJson(404, "用户不存在");
				}
			}
		}else{
			$bank_info = db('mall_cash')->where('uid',input('uid'))->order('add_time desc')->find();
			
			if($bank_info){
				return $this -> toJson(200, '',$bank_info);
			}
		}
	}

	//用户佣金转入余额
	function yonghj_to_money(){
		$user = Db::name('member')-> where('id', input('uid'))->find();
		
		if($user){
			//提现金额
			$up_money = input('money');
			if($up_money<=$user['credit3']){
				
				//手续费
				$poundage = bcmul($up_money, 0.05, 2);					//乘
				
				//实际到账金额
				$add_money = bcsub($up_money, $poundage, 2);			//减
				
				//更新佣金金额
				$user['credit3'] = bcsub($user['credit3'], $up_money, 2); 
				//跟新用户余额
				$user['credit2'] = bcadd($user['credit2'], $add_money, 2);	//加
				
				db('member')->where('id', $user['id'])->update(['credit3' => $user['credit3'],'credit2' =>$user['credit2']]);
				
				//扣除用户佣金
				$data['uid'] 			= $user['id'];
				$data['tid'] 			= 0;
				$data['credittype'] 	= 'credit3';
				$data['price'] 			= -$add_money;
				$data['add_time'] 		= now_time();
				$data['remark'] 		= '佣金转余额';
				$data['type'] 			= 1;			//'0.默认1.佣金2.提现3.红包4.收付款';
				
				$result1 = db('mall_credits')->insert($data);
				
				//佣金手续费日志
				$data['price'] 			= -$poundage;
				$data['credittype'] 	= 'credit3';
				$data['add_time'] 		= now_time();
				$data['type'] 			= 1;
				$data['remark'] 		= '手续费';
				$result2 = db('mall_credits')->insert($data);
				
				//增加余额
				$data['price'] 	 = $add_money;
				$data['credittype'] 	= 'credit2';
				$data['add_time'] 		= now_time();
				$data['remark']  = '佣金转余额';
				$data['type'] 	 = 1;
				
				$result2 = db('mall_credits')->insert($data);
				
				if($result1 && $result2){
					return $this -> toJson(200, '佣金转入余额成功');
				}else{
					return $this -> toJson(408, '佣金转入余额异常');
				}
			}else{
				return $this -> toJson(404, '佣金不足');
			}
		}else{
			return $this -> toJson(404, '用户不存在');
		}
	}

	//佣金记录
	function yongj_record(){
		//根据当前用户获取商户id 
		$credits_list = Db::name('mall_credits')->where('uid',input('uid'))->where('credittype','credit3')->order('add_time asc')->select();
		
		if($credits_list){
			
			for($i=0;$i<count($credits_list);$i++){
				
				if($i==0){
					$credits_list[$i]['balance'] = $credits_list[$i]['price'];
				}else{
					$credits_list[$i]['balance'] = $credits_list[$i-1]['balance'] + $credits_list[$i]['price'];
				}
			}
			return $this->toJson(200,'',$credits_list);
		}
	}
	//用户余额记录
	function yue_jilu(){
		$credits_list = Db::name('mall_credits')
						->where('uid',input('uid'))
						->where('credittype','credit2')
						->where('type','in','1,2,3,4,11,12,16,18')
						->order('add_time asc')->select();
		foreach($credits_list as $key=>$value){
			if($value['type'] == 12 && $value['price']<0){
				unset($credits_list[$key]);
			}
		}
		$credits = array();
		foreach($credits_list as $k=>$v){
			$credits[] = $v;
		}
		
		
		if(count($credits)>0){
			return $this->toJson(200,'',$credits);
		}else{
			return $this->toJson(402,'暂无记录');
		}
	}
	
	//用户鼓励金记录
	function user_jifeng(){
		$credits_list = Db::name('mall_credits')->where('credittype','credit1')->where('uid',input('uid'))->order('add_time desc')->select();
		if($credits_list){
			return $this->toJson(200,'',$credits_list);
		}else{
			return $this->toJson(402,'暂无记录');
		}
	}
	
	//获取用户的资料
	function userInfo(){
		$uid = request() -> param('uid');
		$userInfo=Db::name('member')->where('id',$uid)->find();
		$shopInfo=Db::name('info_agent')->where('u_id',$uid)->find();
		$data[]=$userInfo;
		$data[]=$shopInfo;
		if($data){
			return $this -> toJson(200, 'ok',$data);
		}else{
			return $this -> toJson(408, '数据异常');
		}
	}

	//获取店铺信息
	function get_storeby_id(){
		//获取商家信息
		$store_info = db('info_agent')->where('id',input('store_id'))->find();
		if($store_info){
			return $this -> toJson(200, '', $store_info);
		}else{
			return $this -> toJson(405, '数据异常');
		}
	}
	//获取收款人
	function get_userby_id(){
		//获取商家信息
		$store_info = db('info_agent')->where('id',input('store_id'))->find();
		if($store_info){
			return $this -> toJson(200, '', $store_info);
		}else{
			return $this -> toJson(405, '数据异常');
		}
	}
	
	//获取用户在店铺的鼓励金使用情况
	function apply_score_user(){
		$where['uid'] 			= input('user_id');
		$where['credittype'] 	= 'credit1';
		$where['tid'] 			= input('store_id');
		//获取用户在商家鼓励金获取情况
		$give_score = db('mall_credits')->where($where)->sum('price');
		
		return $this -> toJson(200, '', $give_score);
	}
	
	//后台超级码支付根据订单id获取订单商铺信息
	function get_payinfo(){
		$order=db('line_order')->find(input("order_id"));
		$store_info = db('info_agent')->where('id',$order['agent_id'])->find();
		if($store_info){
			return json(["code"=>200,'','data'=>$store_info,'order'=>$order]);
		}else{
			return $this -> toJson(405, '数据异常');
		}
	}
	//获取附近广告
	function pay_ads(){
		//获取附近店铺广告
		$sql ='select a.id,a.agent_id,a.union_id,a.name,a.address,a.longitude,a.latitude,b.thumb,b.ad_score,b.template_id,b.business_scope,'.
						'ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-a.latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(a.latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-a.longitude*PI()/180)/2),2)))*1000) AS juli'.
						' from long_mall_unionitem  as a LEFT JOIN long_info_agent as b ON a.agent_id = b.id where a.apply = 2 and a.status = 1  order by juli limit 5 ';
		$union_item_list = Db::query($sql); 
		
		if($union_item_list){
			return $this -> toJson(200, '', $union_item_list);
		}else{
			return $this -> toJson(405, '数据异常');
		}
	}
	
	function pay_info(){
		$longitude = input('longitude');
		$latitude = input('latitude');
		
		$pay_log = db('mall_corepaylog')->where('sn',input('sn'))->find();
		$agent_list = null;
		if($pay_log){
			//收款店铺信息
			$agent_info = db('info_agent')->where('id',$pay_log['tid'])->find();
			//检查当前用户是否联盟用户
			if($agent_info && $agent_info['is_round'] == 2){
				//获取联盟信息
				$union_id = db('mall_unionitem')->where('apply',2)->where('status',1)->where('agent_id',$agent_info['id'])->value('union_id');
				
				$sql ='select distinct a.id as agent_id,a.store_name,a.address,a.store_logo,a.ad_score,a.template_id,a.business_scope,'.
							'ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-a.latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(a.latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-a.longitude*PI()/180)/2),2)))*1000) AS juli'.
							' from long_info_agent  as a LEFT JOIN long_mall_unionitem as b ON a.id = b.agent_id where b.apply = 2 and b.status = 1 and a.ad_money>0 and a.id = '.$agent_info['id'].'  order by juli limit 5 ';
			}else{
				$sql ='select id as agent_id,store_name,address,store_logo,ad_score,template_id,business_scope,'.
							'ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli'.
							' from long_info_agent where is_round >0  and ad_money>0  order by juli limit 5 ';
			}
			$agent_list = Db::query($sql); 
			//更新用户信息
			$user_info = db('member')->where('id',$pay_log['uid'])->find();
			$user_info['token'] = md5_salt($user_info['id'],config("salt"));
			$data['pay_log'] = $pay_log;
			$data['agent_list'] = $agent_list;
			$data['user_info'] = $user_info;
			
			//获取收款店铺信息
			$shou_agent = db('info_agent')->where('id',$pay_log['tid'])->find();
			$data['shou_agent'] = $shou_agent;
			
			return $this -> toJson(200, '', $data);
		}else{
			return $this -> toJson(405, 'sn不存在',$pay_log);
		}
	}
	function pay_info1(){
		$longitude = input('longitude');
		$latitude = input('latitude');
		
		$pay_log = db('line_paylog')->where('orderId',input('order_id'))->find();
		$union_item_list = null;
		if($pay_log){
			$sql ='select a.id,a.agent_id,a.union_id,a.name,a.address,a.longitude,a.latitude,b.thumb,b.ad_score,b.template_id,b.business_scope,'.
						'ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-a.latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(a.latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-a.longitude*PI()/180)/2),2)))*1000) AS juli'.
						' from long_mall_unionitem  as a LEFT JOIN long_info_agent as b ON a.agent_id = b.id where a.apply = 2 and a.status = 1 and b.ad_money>0  order by juli limit 5 ';
			$union_item_list = Db::query($sql);
		}
		$data['pay_log'] = $pay_log;
		$data['union_item'] = $union_item_list;
		if($pay_log){
			return $this -> toJson(200, '', $data);
		}else{
			return $this -> toJson(405, '数据异常',$pay_log);
		}
	}
	//订单号查找支付日志
	function get_paylog(){
		$pay_log = db('mall_paylog')->where('sn',input('sn'))->find();
		if($pay_log){
			return json(["code"=>200,"data"=>$pay_log]);
		}else{
			return json(["code"=>404]);
		}
		
	}
	
	//获取纯openid
	function cut_user_openId(){
		$we_config = get_config('payment_config');
		$code = input("code");//获取code
		$appid =strval($we_config['wxpay_appid']);
		$appsecret =strval($we_config['wxpay_appsercet']);
		$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
		//通过code换取网页授权access_token
		$weixin =  file_get_contents($token_url);
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		$openid = $array['openid'];//输出openid
		if(input("just")){//只获取openid;
			return json(["openid"=>$openid]);
		}
		if($openid){
			//检查用户是否存在
			$member = db('member')->where('openid',$openid)->find();
			if($member){
				$member['token'] = md5_salt($member['id'],config("salt"));
				return $this -> toJson(200,'', $member); 
			}else if(input("line_oid")){//线下支付判断是否有线下会员id;
				$line_order=db("line_order")->find(input("line_oid"));
				if(!$line_order['line_member_id']){//如果线下支付没有选择线下会员则注册新会员
					//获取合伙人id，上级id
					$p_user=db("member")->alias('a')
					->join('info_agent b','a.id=b.u_id')
					->field('a.pid,a.pt_id')
					->where('b.id',$line_order['agent_id'])
					->find();
					//创建新用户
					$member_model = new MemberModel();

					$member_model->pid 			= $p_user['pid'];
					$member_model->status		= 0;
					$member_model->agent_type	= 1;
					$member_model->pt_id		= $p_user['pt_id'];
					$member_model->openid 		= $openid;
					$member_model->add_time		=now_time();
					
					$result = $member_model->allowField(true)->save();
					$user_id = $member_model->getLastInsID();
					if($result){
						$this->mc_level($p_user['pid'], $user_id); //记录上下级关系    	 
						  
						$member_model['id'] = $user_id;
						$token=md5_salt($user_id,config("salt"));
						$member_model['token']=$token;
						return $this -> toJson(200,'', $member_model); 
					}else{
						return $this -> toJson(400,"数据异常");
					}
				}
			}else{
				//获取合伙人id，上级id
				$p_user=db("member")->where('id',input('fromuid'))->find();
				//创建新用户
				$member_model = new MemberModel();
				$member_model->pid 			= $p_user['pid'];

				$member_model->status		= 0;
				$member_model->agent_type	= 1;
				$member_model->pt_id		= $p_user['pt_id'];
				$member_model->openid 		= $openid;
				$member_model->add_time		= now_time();
				$result = $member_model->allowField(true)->save();
				$user_id = $member_model->getLastInsID();
				if($result){
					$fromuid = input('fromuid')?input('fromuid'):1;
					$this->mc_level($fromuid, $user_id); //记录上下级关系    	 
					$new_user = db('member')->where('id',$user_id)->find();
					$token=md5_salt($user_id,config("salt"));
					$new_user['token']=$token;
					return $this -> toJson(200,'', $new_user); 
				}else{
					return $this -> toJson(400,"数据异常");
				}
			}
		}else{
			return $this -> toJson(402,"openid null ");
		}
	}
	
	
	//获取支付宝userid
	function cut_user_alibyid(){
		import("payment.dpay.aop.AopClient");
		import("payment.dpay.aop.request.AlipaySystemOauthTokenRequest");
		$code = input("code");//获取code
		$aop = new \AopClient ();
		$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
		$aop->appId = '2016030801195057';
		$aop->rsaPrivateKey = "MIIEowIBAAKCAQEAlzBlevyzabYxwRnG7mTo+KH39kxDXSaxb+iyfRSH9nw0eg7+Ltsx4VyA967S1LktOAo6dp05ty2bk9D5CQrQYu4ci+AKYmdGQNuGteJXeXt8NqBMQ4OgOKz2/wERXk4TZ5DTC4vKTyhhIFt+gcEKcKvY+lXkssY4+4/d9UCDSqErK8uLIQYAgpWNdcZj97YpsxOBxrze/u7bP1Ct2F/z6B1HLWaHYZmz+0Xlo94xCV1SoBs8BVpbDx0B0HTcUWTeQF7z4+SHIySEKtVv2YrW+hc2mLAHziFwikIWF+iuK0j/HN5/gYaAGd5GD0RHtwwi/sFgRjZ9GSEcV5tWm7V/DQIDAQABAoIBAHbedzs+SbV4qR/Aq5atwjoR5opApcosbN+m3gbXyJp0RzIcbZ7behlNCJ00V9EmkrX33MV7knBCLIsIh3SjivntaoZTLPb3adX+g6inf80k2KF+YNfIOoW1ADG4XjZ+PmV0CWqPiw23mr29EfbkltfFVUBlnf0tOooXMBTulwtp/MT0vhAYkNGtDnS8cfRnOekb0CKxTq3m/C+bNJKAUgOGMvxCORTHs1r8v5VJSzn/FwFcbiq6TExpy9D7ImQpbfw2KvXFc+9YJM9xbcMMFlP2sWOToHcC/JcskVJqJbnsxneW2OAsrl9uUkmJ8P5VOXbe+Bi5FF9OiP6pK3rwVGUCgYEAyFgF7O88g/JBv5egIjKNdT52h+oxPiaWNec2A+lymRVNXqmsvDcqI1LCz0mFqHJZOzl96aLbKTl+pbj8VvVSLCYnE/N7WZvGlHr8C3IIbXEUHKJQvn+qn8PJZLXxiT0GvJPSp8mPNlX2swnWn3AbL1Rkozg0m/P+TK8eaAs2jnsCgYEAwTCZ/Iw02KjNOl7utAk/jCVzPckAxfT//JbIKjDNTpAEhlB/NMLnM0f7qM6wOxu6EG7eoIjrTJH0jFHc8+CY96jzblhLmSW//8vMqt3vD7vF10WgPws57m4Znh2mPYIkTymxlPCkJsDYfLCE/ZsT6NldahI9S2ZGgbXDLXPGdhcCgYEApqpTg6AiP8IxYCnLVaeodnjYMolpHcMMAxutm+OBKkjGbJHK2Wkq7OfUmI0ZW+CEyvgw/0Qz/j+OVF9nzQ+YpJG4wKg1XX5x3OPS+dKLoEAJ8yg088VRNEe0KswRe5IBIK/49wx+zz0EVj1BBrJEa0NR1VbUrUh1rWWhbfymDjECgYBONICBjbhu5JZ/xKJY202QTDDEmDPp7u4ZsGhDPBJAdWh/fuKf1y6EweUMRu9sXiMKN/eDgSnPi14114Xca9VAnHI+/xtLWc7JnBS0Lrdx5Q+Hv7XJD6BZ9tQD//il+aL9MOGka23oCjUY9NRBXZ/HqQZ5w/xwI2zzYUMriSyT7QKBgBhunnjrdUi/hBQbl+SRuJ36x8/9gFscXaec4318J6bEKnLaoiuA+s3i/NYyHgT+fdXFylfMv0tKA9joXvBZLfbnI7E7UMU7fqf+ncBQ0dsWhUlsRgC7fY366856FxTC+YV6DhAs55Fh/PZqzJ2FBz8VO+3Z+C/LGgr9o407Alun";
		$aop->alipayrsaPublicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjkJlBPWQkWe+ExtL1z2XMIjsvOwvduz1CVKgxlwfPGbzzBVsmXzEjdnIjHpF6KjGo8MwaGd9wRmsVM3kqMvuHDbBfk4egoKClgzXLYPuUrNK6h5bsz6WY1/8tBlg2xMVg2AabNdHSEwI8z6PDELcfVmkkcOfS+fGzuCnvSYeEIpGzz1uQQPSbHfxNxCcCdkJ0SZfjduX2augFZ+1L/sorJgLxfNxWBcNCyJST1M3Eix5NHOA6iR3iSvkV4z0Yes1uMyv4Rp3nHFs8KMOZOsTmrqvpLWrhEkz7EH5j+v7fjRVmgb42Whz3HxP9tuhDgFC7YpbCfKURZZFqWYUTpTLvQIDAQAB";
		$aop->apiVersion = '1.0';
		$aop->signType = 'RSA2';
		$aop->postCharset='UTF-8';
		$aop->format='json';
		
		$request = new \AlipaySystemOauthTokenRequest ();
		$request->setGrantType("authorization_code");
		$request->setCode($code);
		$result = $aop->execute ( $request); 
		$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
		$resultCode = $result->$responseNode->user_id;
		if($resultCode){
			//检查用户是否存在
			$user_info = db('member')->where('alipay_id',$resultCode)->find();
			if($user_info){
				$user_info['token'] = md5_salt($user_info['id'],config("salt"));
				return $this -> toJson(200,'', $user_info); 
			}else{
				$f_id = input('fromuid')?input('fromuid'):1;
				
				//获取店铺合伙人id，上级id
				$p_user=db("member")->where('id',$f_id)->find();
				//创建新用户
				$member_model = new MemberModel();
				$member_model->nick_name 	=''.time();
				$member_model->pid 			= $f_id;
				$member_model->status		= 1;
				$member_model->agent_type	= 1;
				$member_model->pt_id		= $p_user['pt_id'];
				$member_model->alipay_id 	= $resultCode;
				$member_model->add_time		= now_time();
				
				$result = $member_model->allowField(true)->save();
				$user_id = $member_model->getLastInsID();
				if($result){
					$this->mc_level($f_id, $user_id); //记录上下级关系    	 
					 
					$user_info = db('member')->where('id',$user_id)->find();
					$token=md5_salt($user_id,config("salt"));
					$user_info['token']=$token;
					return $this -> toJson(200,'', $user_info); 
				}else{
					return $this -> toJson(400,"数据异常");
				}
			}
		}else{
			return $this -> toJson(402,"alipay_id null");
		}
	}

	//用户二维码收付款记录
	function user_qrcode_record(){
		//用户收款记录
		$record_list1 = db('mall_credits')->where('tid',input('user_id'))->where('type',12)->where('price','>',0)->where('credittype','credit2')->select();
		//用户付款记录
		$record_list2 = db('mall_credits')->where('uid',input('user_id'))->where('type',12)->where('price','<',0)->where('credittype','credit2')->select();
		
		if($record_list1 || $record_list2){
			//合并数组
			$record_list = array_merge($record_list1,$record_list2);
			//以id进行排序
			$credits_ids = array();
			foreach ($record_list as $record) {
			    $credits_ids[] = $record['id'];
			}
			array_multisort($credits_ids, SORT_DESC, $record_list);
			
			return $this -> toJson(200,'', $record_list);
		}else{
			return $this -> toJson(402,"暂无数据");
		}
	}
	
	function record(){
		$agent_id = session('agent_id');
		return  $this->fetch();
	}
	
	//商家二维码收付款记录
	function records(){
		$agent_id = session('agent_id');  	
		$page=1;
		if(input("page")){
			$page=input("page");
		}
		$where['agent_id'] = $agent_id;
		$where['order_type'] = ['not in','3,4,5'];		
		$where['state'] = 2;		
		$begin=($page-1)*10;
		$record_list = db('log_paylog')
						->where($where)
						->order('add_time desc')
						->limit($begin,10)->select();	
		return json(["list"=>$record_list]);
	}

	//使用鼓励金付款
	function pay_by_score(){
		// 获取短信模板
			$template = db('sms_template') -> find(4);
			
			//$msg = json_decode(htmlspecialchars_decode($template['params']));
			//$msg->name = '10';
			//dump(json_encode($msg));
			//发送短信，提醒商家
			$msg = send_sms(15343353867, $template['tid'], htmlspecialchars_decode($template['params']), $template['sign_name']);
	}
	
	//开启鼓励金营销
	function is_score(){
			$result = db('info_agent')->where('id',input('store_id'))->update(['is_score'=>input('state')]);
			if($result){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
	}
	
	//修改店铺状态，开放店铺，单店铺
	function is_agent_round(){
			$result = db('info_agent')->where('id',input('store_id'))->update(['is_round'=>input('state')]);
			if($result){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
	}
	//修改店铺云商圈状态，开放云商圈，关闭云商圈
	function is_ads(){
			$result = db('info_agent')->where('id',input('store_id'))->update(['is_ads'=>input('state')]);
			if($result){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
	}
	
	//鼓励金抵扣比例
	function score_dikou(){
		$bili = input('bili');
		//鼓励金抵扣比例最低为10
		if(intval($bili) <1){
			return $this -> toJson(403,"鼓励金抵扣比例不能低于1%");
		}else{
			$res = db('info_agent')->where('id',input('store_id'))->update(['ad_score'=>$bili]);
			if($res){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
		}
	}
	
	//鼓励金赠送比例
	function score_give(){
		$bili = input('bili');
		//鼓励金抵扣比例最低为10
		if(intval($bili) <1){
			return $this -> toJson(403,"鼓励金赠送比例不能低于1%");
		}else{
			$res = db('info_agent')->where('id',input('store_id'))->update(['zs_score'=>$bili]);
			if($res){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
		}
	}
	
	//单次广告费
	function ads_money(){
		$ads_money = input('ads_money');
		
		if(intval($ads_money*100) <10){
			return $this -> toJson(403,'单次广告费最低为0.1元');;
		}else{
			$res = db('info_agent')->where('id',input('store_id'))->update(['ad_one'=>$ads_money]);
			if($res){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
		}
	}
	//获取当前用户信息
	function cut_member_info(){
		$member_info = db('member')->where('id',input('uid'))->find();
		if($member_info){
				$token=md5_salt($member_info['id'],config("salt"));
				$member_info['token'] = $token;
				return $this -> toJson(200,'',$member_info);
			}else{
				return json(['code'=>402,'msg'=>'当前用户不存在']);
			}
	}
	
	
	function member_by_openid(){
		//根据openid 查找用户
		$user_info = db('member')->where('openid',input('openid'))->find();
		if($user_info){
				$user_info['token'] = md5_salt($user_info['id'],config("salt"));
				return $this -> toJson(200,'', $user_info); 
			}else{//注册新用户
				$fromuid = input('fromuid')?input('fromuid'):1;
				//获取合伙人id，上级id
				$p_user=db("member")->where('id',$fromuid)->find();
				//创建新用户
				$member_model = new MemberModel();
				$member_model->pid 			= $fromuid;
				$member_model->status		= 1;
				$member_model->agent_type	= 1;
				$member_model->pt_id		= $p_user['pt_id'];
				$member_model->openid 		= input('openid');
				$member_model->nick_name	=''.time();
				$result = $member_model->allowField(true)->save();
				$user_id = $member_model->getLastInsID();
				if($result){
					$this->mc_level($fromuid, $user_id); //记录上下级关系    	 
					$new_user = db('member')->where('id',$user_id)->find();
					$token=md5_salt($user_id,config("salt"));
					$new_user['token']=$token;
					return $this -> toJson(200,'', $new_user); 
				}else{
					return $this -> toJson(400,"数据异常");
				}
			}
	}
	
	//获取附近联盟信息
	function union_list_distance(){
		$user_id = input('uid');
		//获取当前用户店铺
		$agent_info  = db('info_agent')->where('u_id',$user_id)->find();
		$latitude = '113.026533';
		$longitude ='25.80212';
		
		if($agent_info){
			if($agent_info['latitude'] && strlen($agent_info['latitude'])>2){
				$latitude = $agent_info['latitude'];
			}
			if($agent_info['latitude'] && strlen($agent_info['latitude'])>2){
				$longitude = $agent_info['longitude'];
			}
			$next_page =  intval(input('next_page')) ? intval(input('next_page')) : 1;
			//获取店铺附近联盟
			$sql = 'select id,name,thumb,unnion_ads_money,scope,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli from long_mall_unionstore where status=2 and state=1 limit '.(($next_page-1)*20).',20';
			$union_list=db::query($sql);
			if($union_list){
					$data['agent_info'] = $agent_info;
					$data['union_list'] = $union_list;
				return $this -> toJson(200,'',$data);
			}else{
				return $this -> toJson(401,"暂无联盟");
			}
		}else{
			return $this -> toJson(402,"未开通店铺");
		}
	}

	//获取联盟信息
	function union_info_by_id(){
		//获取当前用户店铺
		$agent_info  = db('info_agent')->where('u_id',input('uid'))->find();
		//获取联盟信息
		$union_info = db('mall_unionstore')->where('id',input('union_id'))->find();
		//查找用户是否在此联盟
		//$item_where['apply'] = 2;
		$item_where['status'] = 1;
		$item_where['agent_id'] = $agent_info['id'];
		$item_where['union_id'] = $union_info['id'];
		$union_item = db('mall_unionitem')->where($item_where)->find();
		//不在该联盟
		$in_this_union = 2;
		$in_apply = 0;
		//在该联盟
		if($union_item){
			$in_this_union = 1;
			$in_apply = $union_item['apply'];
		}
		
		if($union_info){
			$data['agent_info'] = $agent_info;
			$data['union_info'] = $union_info;
			$data['in_this_union'] = $in_this_union;
			$data['in_apply'] = $in_apply;
			return $this -> toJson(200,'',$data);
		}else{
			return $this -> toJson(402,"联盟不存在");
		}
	}


	//获取成员联盟列表
	function union_leaguer_list(){
		$where['union_id'] = input('union_id');
		$where['apply'] = 2;
		$where['status'] = 1;
		
		$union_item_list = db('mall_unionitem')->where($where)->select();
		if($union_item_list){
			return $this -> toJson(200,'',$union_item_list);
		}else{
			return $this -> toJson(402,"暂无成员");
		}
	}

	 //申请加入联盟
    public function union_apply(){
    	$union_id = input('union_id');
    	//根据用户id查找用户信息想
    	$agent_info = db('info_agent')->where('u_id',input('uid'))->find();
		$agent_id = $agent_info['id'];
		//查找联盟信息
		$union_info = Db::name('mall_unionstore')->where('id',$union_id)->where('state',1)->find();
		if(!$union_info){
			return json(["code"=>401,"msg"=>"联盟已解散"]);
		}
		if($union_info['agent_id'] == $agent_id){
			return json(["code"=>404,"msg"=>"抱歉，暂不支持加入自己联盟"]);
		}
		//检查是否已加入该联盟
		$in_unionstore = db('mall_unionitem')->where('agent_id',$agent_id)->where('union_id',$union_id)->where('status',1)->find();
		if($in_unionstore){
			return json(["code"=>405,"msg"=>"您已加入该联盟,不需再申请"]);
		}
			//获取店铺信息
			if($union_info && $agent_info){
				$union_item = array(
					'union_id'			=> $union_info['id'],
					'agent_id' 			=> $agent_info['id'],
					'lm_name'			=> $union_info['name'],
					'add_time' 			=> now_time(),
					'store_tel' 		=> $agent_info['store_tel'],
					"address"			=> $agent_info['address'],
					"longitude"			=> $agent_info['longitude'],
					"latitude"			=> $agent_info['latitude'],
					"apply"				=> 1,
					"thumb"				=> $agent_info['thumb'],
					"store_name"		=> $agent_info['store_name'],
					"business_scope"	=> $agent_info['business_scope'],
					"unnion_ads_money"	=> $union_info['unnion_ads_money'],
					"union_main_agent"  => $union_info['agent_id']
					);
					$result = db('mall_unionitem')->insert($union_item);
					//修改店铺联盟状态
					db('info_agent')->where('id', $agent_id)->update(['is_union' => 3]);
				if($result){
					return json(["code"=>200,"msg"=>"申请成功等待审核"]);
				}else{
					return json(["code"=>404,"msg"=>"申请失败"]);
				}
			}else{
				return json(["code"=>405,"msg"=>"申请失败"]);
			}
    }
	/**
	 * 创建联盟
	 */
	public function create_union(){
		//根据用户id查找用户信息想
    	$agent_info = db('info_agent')->where('u_id',input('uid'))->find();
		
    	$store_id = $agent_info['id'];
    	//检查用户是否已创建联盟
    	$unionstore =  db('mall_unionstore')->where('agent_id',$store_id)->where('state',1)->find();
    	if($unionstore){
    		return $this -> toJson(401,"抱歉，暂不支持重复创建联盟");
    	}
		/*
		//检查当前用户是否已加入其它联盟
		$sql = 'select * from long_mall_unionitem where agent_id = '.$store_id.' and (apply =2 or apply =1) and status =1';
    	$union_item=Db::query($sql);
		if($union_item){
			return $this -> toJson(402,"您已申请进入其它联盟，暂时不能创建联盟");
		}*/
			$param=input();
			/*
			//佣金必须大等于0.1
			if(floor($param['ads_one']*10) <1){
				return $this -> toJson(403,"联盟佣金不能小于0.1元");
			}
			*/
			$union_data['agent_id'] 		= $store_id;
			$union_data['store_name'] 		= $agent_info['store_name'];
			$union_data['name'] 			= $param['name'];
			$union_data['address'] 			= $agent_info['address'];
			$union_data['tel'] 				= $param['mobile'];
			$union_data['thumb'] 			= $param['thumb'];
			$union_data['longitude'] 		= $agent_info['longitude'];
			$union_data['latitude'] 		= $agent_info['latitude'];
			$union_data['content'] 			= $param['content'];
			$union_data['scope'] 			= $param['scope'];
			$union_data['unnion_ads_money'] = 0.1;
			$union_data['add_time'] 		= now_time();
			//新增联盟信息
			$rest = db('mall_unionstore')->insert($union_data);
			//获取联盟id
			$cut_union_id = db('mall_unionstore')->getLastInsID();
			
			//修改店铺联盟状态
			db('info_agent')->where('id', $store_id)->update(['is_union' => 3]);
			
			//新增联盟详情
         	$store_info =Db::name('mall_unionstore')->alias('a')
		   		->join('info_agent b','a.agent_id=b.id','LEFT')
		   		->field('a.id as union_id,a.unnion_ads_money as ads_money, a.name as lm_name,b.*')
		   		->where('a.id',$cut_union_id)->find();
         		
			$union_item = array(
				'union_id'			=> $store_info['union_id'],
				'agent_id' 			=> $store_info['id'],
				'lm_name'			=> $store_info['lm_name'],
				'add_time' 			=> now_time(),
				'store_tel' 		=> $store_info['store_tel'],
				"address"			=> $store_info['address'],
				"longitude"			=> $store_info['longitude'],
				"latitude"			=> $store_info['latitude'],
				"apply"				=> 1,
				"thumb"				=> $store_info['thumb'],
				"store_name"		=> $store_info['store_name'],
				"business_scope"	=> $store_info['business_scope'],
				"unnion_ads_money"	=> $store_info['ads_money'],
				"union_main_agent"  => $store_info['id']
				);
			$res = db('mall_unionitem')->insert($union_item);
			
			if($rest) {
				return $this -> toJson(200,"创建联成功,等待审核");
	        } else {
	        	return $this -> toJson(404,"创建联盟失败");
	        }
    }

	/**
	 * 我的联盟
	 */
	function my_union(){
		//根据用户id查找用户信息想
		$store_info = db('info_agent')->where('u_id',input('uid'))->find();
		//检查联盟主中是否有该用户
		$unionstore =  db('mall_unionstore')->where('agent_id',$store_info['id'])->where('state',1)->find();
		if($unionstore && $unionstore['state'] != 3){	//联盟主或申请联盟主，且联盟未解散
			return $this -> toJson(201,'',$unionstore);
		}else{
			//检查用户是否加入联盟
			$item_where['agent_id'] = $store_info['id'];
			$item_where['status'] = 1;
			$union_item = db('mall_unionitem')->where($item_where)->find();
			
			if($union_item){//联盟成员
				//获取当前用户所在联盟信息
				$unionstore =  db('mall_unionstore')->where('id',$union_item['union_id'])->where('state',1)->find();
				
				$union_info['union_item'] = $union_item;
				$union_info['union_store'] = $unionstore;
				
				return $this -> toJson(202,'',$union_info);
			}else{
				return $this -> toJson(402,'您还未加入联盟');
			}
		}
	}
	
	//联盟主退出联盟
	function back_union(){
			//根据用户id查找用户信息想
			$store_info = db('info_agent')->where('u_id',input('uid'))->find();
			
			//获取联盟信息
			$unionstore = db('mall_unionstore')->where('agent_id',$store_info['id'])->where('state',1)->where('status',2)->find();
			if($unionstore){
				//查找第二个进入联盟成员
				$unionitem = db('mall_unionitem')->where('union_id',$unionstore['id'])->where('apply',2)->where('status',1)->order('add_time')->limit(2)->select();
				if($unionitem && count($unionitem)<2){
					//冻结联盟(联盟主id改为0)
					$dong_res = db('mall_unionstore')->where('agent_id',$store_info['id'])->update(['state' => 3,'agent_id'=>0]);
					//修改当前用户所在联盟成员列表信息
					$cut_unionitem = db('mall_unionitem')
									 ->where('union_id',$unionstore['id'])
									 ->where('agent_id',$store_info['id'])
									 ->where('apply',2)
									 ->where('status',1)
									 ->update(['status' => 2,'go_time'=>now_time()]);
					//修改店铺联盟状态
					db('info_agent')->where('id',$store_info['id'])->update(['is_union' => 1,'is_round'=>0]);
					if($dong_res && $cut_unionitem){
						return json(["code"=>200,"msg"=>"解散联盟成功"]);
					}else{
						return json(["code"=>402,"msg"=>"退出联盟失败"]);
					}
				}else{
					if($unionitem){
						//修改联盟主
						$uprest = db('mall_unionstore')->where('agent_id',$store_info['id'])->update(['agent_id' => $unionitem[1]['agent_id']]);
						if($uprest){
							//删除原联盟主
							$del_res = db('mall_unionitem')->where('id', $unionitem[0]['id'])->delete();
							//修改店铺联盟状态
							db('info_agent')->where('id',$store_info['id'])->update(['is_union' => 1,'is_round'=>0]);
							if($del_res){
								return json(["code"=>200,"msg"=>"退出联盟成功"]);
							}else{
								return json(["code"=>402,"msg"=>"删除原联盟主失败"]);
							}
						}else{
							return json(["code"=>403,"msg"=>"更改联盟主失败"]);
						}
					}else{
						return json(["code"=>404,"msg"=>"该联盟不存在"]);
					}
					
				}
			}else{
				return json(["code"=>404,"msg"=>"数据异常"]);
			}
	}


	//移出联盟成员
	function remove_member(){
			//根据用户id查找用户信息想
			$store_info = db('info_agent')->where('u_id',input('uid'))->find();
			//查询退出用户所在联盟详情
			$where['agent_id'] 		= input('agent_id');
			$where['apply'] 		= 2;
			$where['status'] 		= 1;
			$where['union_id'] 		= input('union_id');
			//被移除成员信息
			$union_item = db('mall_unionitem')->where($where)->find();
			if($union_item){
				//自己申请退出
				if(input('agent_id') == $store_info['id']){
					$resul = db('mall_unionitem')->where($where)->update(['status' => 2,'go_time'=>now_time()]);
					if($resul){
						//检查用户是否加入其它联盟
						$item_where['agent_id'] 		= input('agent_id');
						$item_where['apply'] 		= 2;
						$item_where['status'] 		= 1;
						$union_item_list = db('mall_unionitem')->where($item_where)->select();
						if(count($union_item_list)<1){
							//修改店铺联盟状态
							db('info_agent')->where('id', $store_info['id'])->update(['is_union' => 1,'is_round'=>0]);
						}
						return json(["code"=>201,"msg"=>"退出联盟成功"]);
					}else{
						return json(["code"=>402,"msg"=>"退出失敗"]);
					}
				}
				//联盟主移出
				$unionstore = db('mall_unionstore')->where('agent_id',$store_info['id'])->find();
				if($unionstore && $unionstore['id'] == $union_item['union_id']){
					$resul = db('mall_unionitem')->where($where)->update(['status' => 2,'go_time'=>now_time()]);
					if($resul){
						//检查用户是否加入其它联盟
						$item_where['agent_id'] 	= input('agent_id');
						$item_where['apply'] 		= 2;
						$item_where['status'] 		= 1;
						$union_item_list = db('mall_unionitem')->where($item_where)->select();
						if(count($union_item_list)<1){
							//修改店铺联盟状态
							db('info_agent')->where('id', $store_info['id'])->update(['is_union' => 1,'is_round'=>0]);
						}
						return json(["code"=>202,"msg"=>"移出成功"]);
					}else{
						return json(["code"=>403,"msg"=>"移出失败"]);
					}
				}
			}else{
				return json(["code"=>401,"msg"=>"您还不是该联盟成员"]);
			}
	}

	//联盟成员信息
	function sel_union_list(){
		//根据用户id查找用户信息想
		$store_info = db('info_agent')->where('u_id',input('uid'))->find();
		$unionstore = db('mall_unionstore')->where('agent_id',$store_info['id'])->find();
		//检查用户是否联盟主
		if($unionstore){
			//检查当前用户是否已加入其它联盟
			$sql = 'select * from long_mall_unionitem where union_id = '.$unionstore['id'].' and (apply =2 or apply =1) and status =1 order by id desc';
	    	$union_item=Db::query($sql);
			$data['union_item'] = $union_item;
			$data['cut_agent_id'] = $store_info['id'];
			return json(["code"=>200,"data"=>$data]);
		}else{
			return json(["code"=>403,"msg"=>"改联盟不存在"]);
		}
	}

	 //同意申请
   public function audit_ok(){
   		$item_id = input('item_id');
   		$is_yes = input('is_yes');
		$union_item = db('mall_unionitem')->where('id',$item_id)->where('apply',1)->find();
		if($union_item){
			//更新申请状态
			$result = db('mall_unionitem')->where('id',$item_id)->update(['add_time' => now_time(),'apply'=>$is_yes]);
			if($result){
				if($is_yes == 2){
					//修改用户店铺状态
					$unionitem = db('mall_unionitem')->where('id',$item_id)->find();
					$res = db('info_agent')->where('id',$unionitem['agent_id'])->update(['is_round' => 2,'is_union' => 2]);
					if(!$res){
						return json(["code"=>403,"msg"=>"修改店铺信息失败"]);
					}
					return json(["code"=>200,"msg"=>"添加联盟成员成功"]);
				}else{
					return json(["code"=>402,"msg"=>"已拒绝该申请"]);
				}
			}else{
				return json(["code"=>402,"msg"=>"添加失败"]);
			}
		}else{
			return json(["code"=>401,"msg"=>"该申请已处理"]);
		}
		
   }

}
